package top.maochang.hou.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import top.maochang.hou.dao.RoleDao;
import top.maochang.hou.dao.SecurityDao;
import top.maochang.hou.dao.UserDao;
import top.maochang.hou.dao.impl.RoleDaoImpl;
import top.maochang.hou.dao.impl.SecurityServiceImpl;
import top.maochang.hou.dao.impl.UserDaoImpl;
import top.maochang.hou.entity.SysRole;
import top.maochang.hou.entity.SysUser;
import top.maochang.hou.tools.Result;
import top.maochang.hou.tools.UserContent;
import top.maochang.hou.tools.WebUtlis;
import top.maochang.hou.vo.PageVo;
import top.maochang.hou.vo.SysUserVo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@WebServlet(name = "user", value = "/user/*")
@Slf4j
public class UserServlet extends BaseServlet{

    /**
     * 去登录
     */
    protected void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getRequestDispatcher("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }

    /**
     * 去首页
     */
    protected void toIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

    /**
     * 登录路径逻辑
     */
    public void  doLoginServlet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取输入的帐号密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //封装用户数据，成为Shiro能认识的token标识
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        UserDao loginService = new UserDaoImpl();
        //将封装用户信息的token进行验证
        boolean isLoginSuccess = loginService.login(token);
        ObjectMapper objectMapper=new ObjectMapper();
        if (!isLoginSuccess) {
            //重定向到未登录成功页面
            String msg = objectMapper.writeValueAsString(new Result<>(2001,"登录失败"));
            resp.getWriter().write(msg);
            return;
        }
        //记录登录状态
        SecurityDao securityDao=new SecurityServiceImpl();
        SysUser sysUser = securityDao.findPasswordByLoginName(username);
        System.err.println(sysUser);
        //把User对象放到会话当中
        UserContent.setUser(sysUser);
        Result rs=new Result<>(2000,"登录成功");
        String msg = objectMapper.writeValueAsString(rs);
        resp.getWriter().write(msg);
    }

    /**
     * 退出登录
     */
    public  void doLogoutServlet(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        UserDao loginService = new UserDaoImpl();
        loginService.logout();
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }


    /**
     * 用户管理
     * 查询所有用户
     */
    public void  getUserList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, InvocationTargetException, IllegalAccessException, SQLException {
        ObjectMapper objectMapper = WebUtlis.getObjectMapper();
        HashMap hashMap=new HashMap();
        try {
            UserDao userDao=new UserDaoImpl();
            SysUser sysUser=new SysUser();
            WebUtlis.copyParmToBean(req.getParameterMap(), sysUser);
            PageVo pageVo=new PageVo();
            WebUtlis.copyParmToBean(req.getParameterMap(), pageVo);
            List<SysUser> users = userDao.getUsers(sysUser,pageVo);
            List<SysUserVo> userVos=new ArrayList<>();
            for (SysUser user : users) {
                SysUserVo sysUserVo=new SysUserVo();
                //属性拷贝
                BeanUtils.copyProperties(sysUserVo,user);
                //调用通过id查询角色的方法
                RoleDao roleDao=new RoleDaoImpl();
                List<SysRole> roleListrByUserId = roleDao.getRoleListrByUserId(user.getId().toString());
                //添加角色集合
                sysUserVo.setSysRoles(roleListrByUserId);
                //新组装数据添加
                userVos.add(sysUserVo);
            }
            hashMap.put("code",0);
            hashMap.put("msg","查询数据成功");
            hashMap.put("data",userVos);
            hashMap.put("count",userDao.getUsersCount());
            resp.getWriter().write(objectMapper.writeValueAsString(hashMap));
        } catch (Exception e) {
            e.printStackTrace();
            hashMap.put("code",0);
            hashMap.put("msg","查询数据失败");
            hashMap.put("data",null);
            hashMap.put("count",0);
            resp.getWriter().write(objectMapper.writeValueAsString(hashMap));
            throw  new RuntimeException(e);
        }
    }

    /**
     * 添加用户信息
     *
     */
    public  void  addUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        try {
            UserDao userDao=new UserDaoImpl();
            SysUser sysUser=new SysUser();
            //用户基本信息
            WebUtlis.copyParmToBean(req.getParameterMap(),sysUser);
            //角色id
            String roleIds = req.getParameter("roleIds");
            String[] roleIdsArray = roleIds.split(",");
            //1.操作用户信息表
            boolean  userFlag = userDao.addUser(sysUser);
            //2.查询用户的最大值
            Long userId = userDao.addUserMaxId();
            //3.操作用户角色信息关联表
            boolean userRoleFlag = userDao.addUserRole(roleIdsArray, String.valueOf(userId));
            boolean flag=false;
            if(userFlag==true&&userRoleFlag==true){
                flag=true;
            }
            getObjectMapper(resp,flag,200,201,"插入成功","插入失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw  new  RuntimeException(e);
        }
    }


    /**
     * 删除用户信息
     * /user/delUser
     */
    public  void  delUser(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        String id = request.getParameter("id");
        SysUser user = (SysUser)UserContent.getUser();
        ObjectMapper objectMapper = WebUtlis.getObjectMapper();
        String s="";
        if(id.equals(user.getId().toString())){
            s = objectMapper.writeValueAsString(new Result<>(201, "当前为登录用户不能删除"));
            response.getWriter().write(s);
            return;
        }
        UserDao userDao=new UserDaoImpl();
        boolean userFlag = userDao.delUser(id);
        String ids = request.getParameter("ids");
        String[] split = ids.split(",");
        boolean UserRoleFlag=false;
        for (String i : split) {
             UserRoleFlag = userDao.delUserRole(i, id);
        }
        boolean b=false;
        if(userFlag==true&&UserRoleFlag==true) {
            b=true;
        }
        getObjectMapper(response, b,200,201,"删除成功","删除失败");
    }

    /**
     * 更改用户状态
     * user/updateUser
     */
    public  void  updateUserStatus(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        UserDao userDao=new UserDaoImpl();
        String userId = request.getParameter("userId");
        String state = request.getParameter("state");
        ObjectMapper objectMapper = WebUtlis.getObjectMapper();
        String s="";
        SysUser user = (SysUser)UserContent.getUser();
        System.out.println();
        if(userId.equals(user.getId().toString())){
            s = objectMapper.writeValueAsString(new Result<>(201, "当前为登录用户不能更改状态"));
            response.getWriter().write(s);
            return;
        }
        boolean b = userDao.updateStatus(userId,state);
        getObjectMapper(response, b,200,201,"修改状态成功","修改状态失败");

    }

    /**
     * 修改用户信息
     */
    public  void   updateUser(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        UserDao userDao=new UserDaoImpl();
        SysUser sysUser=new SysUser();
        //用户基本信息
        WebUtlis.copyParmToBean(request.getParameterMap(),sysUser);
        //角色id
        String roleIds = request.getParameter("roleIds");
        String[] roleIdsArray = roleIds.split(",");
        boolean b = userDao.updateUser(sysUser, roleIdsArray);
        getObjectMapper(response, b,200,201,"修改成功","修改失败");
    }


    /**
     * 重置用户密码
     */
    void  resetUserPassWord(HttpServletRequest request,HttpServletResponse response){
        try {
            String userId=request.getParameter("userId");
            System.out.println(userId);
            UserDao userDao=new UserDaoImpl();
            boolean b = userDao.updateUserPassword(userId);
            getObjectMapper(response, b,200,201,"重置成功","重置失败");
        } catch (Exception e) {
            e.printStackTrace();
            new RuntimeException(e);
        }
    }

    /**
     * 避免代码冗余
     * @param response
     * @param b
     * @param successCode
     * @param failCode
     * @param successMsg
     * @param failMsg
     * @throws IOException
     */
    private void getObjectMapper(HttpServletResponse response, boolean b,Integer successCode,Integer failCode,String successMsg,String failMsg ) throws IOException {
        ObjectMapper objectMapper = WebUtlis.getObjectMapper();
        String s="";
        if(b){
            s = objectMapper.writeValueAsString(new Result<>(successCode, successMsg));
            response.getWriter().write(s);
        }else {
            s= objectMapper.writeValueAsString(new Result<>(failCode,failMsg));
            response.getWriter().write(s);
            throw  new RuntimeException();
        }
    }


    /**
     * 订单添加Servlet
    */
    public void  orderAddServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("order-add.jsp").forward(req, resp);
    }

    /**
     * 数据查询Servelt
     */
    public  void  orderListServlet(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        req.getRequestDispatcher("order-list.jsp").forward(req, resp);
    }

}
